<template>
  <div class="amap-page-container">
    <el-form :inline="true" label-width="130px">
      <el-row>
        <el-col :span="24" style="width:100%;">
          <el-form-item label="搜索地址">
            <el-input id="search" style="width:575px;" v-model="searchKey" placeholder="地址名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button  type="info" plain @click="searchByHand">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="tip-box" id="searchTip"></div>
    </el-form>

    <el-amap
      vid="amap"
      :zoom="zoom"
      class="amap-demo"
      defaultCursor="pointer"
      style="width:90%;margin-left:5%;"
      :center="center"
      :amapManager="amapManager"
      :events="events"
      :plugin = "plugin"
      >
      <el-amap-marker vid="component-marker" :position='clickPosition'></el-amap-marker>
    </el-amap>
    <ul>
      <li v-for="item in result" :key="item.id">{{item.name}}</li>
    </ul>

</div>
</template>

<script>
import {AMapManager} from "vue-amap"
  let amapManager=new AMapManager();
  let infoWindow;
  export default {
    props: {
      dataForm: Object,
      regionAllName:String
    },
    data() {
      let vm = this;
      return {
        zoom:16,
        center: [106.748648,26.563406],
        result:[],
        address: "",
        radius:300,
        toSearch:false,
        clickPosition:  [106.748648,26.563406],
        searchKey: this.regionAllName,//vm.dataForm.regionAllName,
        amapManager,
        map:null,
        longitude: vm.dataForm.longitude === null ? 106.748648:vm.dataForm.longitude,
        latitude: vm.dataForm.latitude === null ? 26.563406:vm.dataForm.latitude,
        poiPicker:null,
        events:{
          init(o){
            vm.map=o;
          },
          'click': (e) => {
            vm.dataForm.longitude = e.lnglat.lng
            vm.dataForm.latitude = e.lnglat.lat
            vm.clickPosition = [e.lnglat.lng,e.lnglat.lat]
            vm.getAddressName([e.lnglat.lng ,e.lnglat.lat]);
          }
        },
        plugin: ['ToolBar', {
          pName: 'MapType',
          defaultType: 0,
          events: {
            init(o) {
            }
          }
        },{
          pName: 'Scale',
          events: {
            init(instance) {
            }
          }
        },{
          pName: 'Geolocation',
          buttonPosition: 'RB',
          events: {
            init(o) {
               vm.map=o;
              // o 是高德地图定位插件实例
              // o.getCurrentPosition((status, result) => {
              //   if (result && result.position) {
              //     vm.zoom = 16
              //     vm.center = [result.position.lng, result.position.lat];
              //     // self.loaded = true;
              //     vm.$nextTick();
              //   }
              // });
            }
          }
        }]
      };
    },
    watch:{
      map:function(){
        if(this.map!=null){
          //this.initSearch();
        }
      }
    },
    mounted() {
      // this.initSearch()
    },
    methods:{
      initSearch(datalongitude,datalatitude){
        let longitude = datalongitude === null ? 106.748648:datalongitude
        let latitude = datalatitude === null ? 26.563406:datalatitude
        this.clickPosition = [longitude,latitude]
        if(datalongitude === null){
          this.getLocatoinLatLng()
        }
        this.getAddressName(this.clickPosition)
        this.center = [longitude,latitude]
        this.searchKey = this.regionAllName.replace(/,/g,"");
        let vm=this;
        let map=this.amapManager.getMap();
        let marker = new AMap.Marker();
        let infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(0, -20)
        });
        this.toSearch=true;
        AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
          var poiPicker = new PoiPicker({
              input: 'search', //输入框id
              placeSearchOptions: {
                map: map,
                pageSize: 10
              },//地点搜索配置
              suggestContainer:'searchTip',//输入提示显示DOM
              searchResultsContainer:'searchTip'//搜索结果显示DOM
          });
          vm.poiPicker=poiPicker;
           poiPicker.on('poiPicked', function(poiResult) {
            let source = poiResult.source;
            let poi = poiResult.item;
            if (source !== 'search') {
                poiPicker.searchByKeyword(poi.name);
            } else {
              poiPicker.clearSearchResults();
              vm.center=[poiResult.item.location.lng,poiResult.item.location.lat];
              vm.clickPosition = [poiResult.item.location.lng,poiResult.item.location.lat];
              vm.address=poi.name;
              vm.searchKey=poi.name;
              vm.getAddressName(vm.center)
            }
          });
          // poiPicker.searchByKeyword(vm.searchKey); // 搜索出现相识地址的方法
          // poiPicker.onCityReady(function() {
          //   poiPicker.suggest('美食'); // 推荐搜索的
          // });
        });
      },
      getAddressName(lnglat){
        let vm = this
        let geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
        geocoder.getAddress(lnglat, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              let addressName= '地址：'+result.regeocode.formattedAddress+'<br /> 坐标：['+lnglat+']';
              if(infoWindow === null){
                infoWindow.close();
              }
              let map=vm.amapManager.getMap();
              var info = [];
              // info.push("<div><div><img style=\"width:30px;height:30px;\" src='../../../static/img/favicon.ico' /><span>东冠智云</span></div> ");
              info.push(addressName +'</div></div>');
              infoWindow = new AMap.InfoWindow({
                  content: info.join("")  //使用默认信息窗体框样式，显示信息内容
              });
              infoWindow.open(map, lnglat);
            }
          }
        });
      },

      getLocatoinLatLng(){
        let vm = this
        let geocoder = new AMap.Geocoder({
          radius: 0.5,
          extensions: "all"
        });
        geocoder.getLocation(vm.regionAllName, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            vm.center = [result.geocodes[0].location.lng,result.geocodes[0].location.lat]
            vm.clickPosition = [result.geocodes[0].location.lng,result.geocodes[0].location.lat]
            vm.getAddressName([result.geocodes[0].location.lng,result.geocodes[0].location.lat])
          }
        });
      },
      searchByHand(){
        if(this.searchKey!=''){
          this.poiPicker.searchByKeyword(this.searchKey);
        }
      }
    }
  };
</script>

<style scoped>
.amap-page-container {
    height: 500px;
    width: 100%;
    position: relative;
    margin-bottom: 30px;
  }
  .search-box{
    position: absolute;
    z-index: 5;
    width: 90%;
    left: 5%;
    top: 10px;
    height: 30px;
  }
  .tip-box{
    width: 60%;
    max-height:300px;
    margin-top: 10px;
    margin-left: 18%;
     z-index: 5;
    position: absolute;
    top: 30px;
    overflow-y: auto;
    background-color: #fff;
  }
</style>
